<template>
    <div class= "zd-lifeMessenger wrap-table">
        <el-tabs v-model="periodModel" type="card">
            <el-tab-pane label="孕前期" name="1">
            </el-tab-pane>
            <el-tab-pane label="怀孕期" name="2">
            </el-tab-pane>
            <el-tab-pane label="儿童期（0-24个月）" name="3">
            </el-tab-pane>
            <el-tab-pane label="儿童期（25-60个月）" name="4">
            </el-tab-pane>
        </el-tabs>

          <!-- 查询区域 -->
        <el-form ref="form" :model="searchData" label-width="120px" class="clearfix">

            <el-form-item label="研究组别" class="pull-left" style="width:200px">
                <el-select v-model="searchData.groupType"  placeholder="请选择">
                    <el-option
                        v-for="item in studyOptions"
                        :key="item.value"
                        :label="item.Name"
                        :value="item.value">
                    </el-option>
                  </el-select>
            </el-form-item>

            <el-form-item label="" class="pull-left">
                <el-input v-model="searchData.articleName" placeholder="请输入文章标题" clearable>
                </el-input>
            </el-form-item>
            <!-- 操作区域 -->
            <div class="pull-left">
                <el-button   @click="queryHandler" class=" mg-lr-20 pd-bt">查询</el-button>
                <el-button type="primary" @click="addHandler" class="pull-right pd-bt">添加</el-button>
            </div>
        </el-form>
        <!-- table 展示  -->
        <template>
            <el-table
                :data="table.tableData"
                border empty-text="当前列表为空"
                v-loading="loading"
                element-loading-text="加载中"
                style="width: 100%"
            >
                <el-table-column
                    align="center"
                    label="编号"
                    width="70"
                >
                    <template slot-scope="scope">
                      {{scope.row.ArticleIndex}}
                    </template>
                </el-table-column>
                <el-table-column
                    prop="ArticleTitle"
                    label="文章标题"
                    min-width="240"
                    align="left"
                >
                </el-table-column>
                <el-table-column
                      prop="GroupType"
                      label="研究组别"
                      :formatter="GroupTypeFilter"
                      width="200"
                      align="center"
                >
                </el-table-column>
                <el-table-column
                    label="操作"
                    width="300"
                    align="center"
                >
                    <template slot-scope="scope">
                       <el-button
                          size="small"
                          type="text"
                          @click="changePositionHandler(1,scope.$index, scope.row )"
                        >
                           <span class="arrow-top"></span>
                      </el-button>
                      <el-button
                          size="small"
                          type="text"
                          @click="changePositionHandler(-1,scope.$index, scope.row)"
                      >
                           <span class="arrow-bottom"></span>
                      </el-button>
                      <el-button
                          @click="handleClick(scope.row)"
                          type="text"
                          size="small"
                          >
                          修改
                      </el-button>
                      <el-button
                          type="text"
                          size="small"
                          @click="deleteHandler(scope.$index, scope.row)"
                        >
                          删除
                      </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </template>


       <!-- 对话框 -->

        <el-dialog
          :title="dialogData.title"
          :close-on-click-modal="false"
          :visible.sync="dialogData.isShow"
          @close="closeDialog()"
          :append-to-body="true" top="0"
        >
        <!-- rules="rules" -->
           <el-form :model="formData" label-position="left"  :rules="rules" ref="addressForm">
              <el-form-item label="信使标题" label-width="100px" prop= "ArticleTitle">
                  <el-input v-model="formData.ArticleTitle" ></el-input>
              </el-form-item>
              <el-form-item label="信使内容" prop="ArticleContent">
                      <Editor
                            class= "editor"
                            v-if= "hackReset"
                            @onchangeEditor="onchangeEditor"
                            tbSel="editor"
                            :editorContent="formData.ArticleContent"
                      />
              </el-form-item>
              <el-form-item label="适用阶段" label-width="100px"  >
                   <el-select v-model="formData.Period"  placeholder="请选择">
                    <el-option
                        v-for="item in applicableOptiona"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                  </el-select>
              </el-form-item>
              <el-form-item label="研究组别" label-width="100px"   >
                   <el-select v-model="formData.GroupType"  placeholder="请选择">
                    <el-option
                        v-for="item in studyOptions"
                        :key="item.value"
                        :label="item.Name"
                        :value="item.value">
                    </el-option>
                  </el-select>
              </el-form-item>
           </el-form>

            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogData.isShow = false">取 消</el-button>
              <el-button type="primary" @click="saveHandler" v-loading.fullscreen.lock="fullscreenLoading">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import Editor from '@/components/editor/list'
import {DIC_PERIODB} from '@/utils/localDic'
  const ArticleContent =(rule, value, callback) =>{
    if( !value ||
        value.indexOf('<p><br></p>')> -1 && value.indexOf('</p><p><br></p>') == -1){
      return callback(new Error('必填项'))
    }else{
        callback()
    }
  }

export default {
    name: 'lifeMessenger',

    components: {
       Editor
    },

    data() {
      return {
          fullscreenLoading: false,
          periodModel:"1",
          hackReset:false,
          Period: '1',  //记录数值
          searchData: {   // 查询from
                period: '1',
              groupType: '1',
              articleName: '',
          },
          loading:true,
          table:{  //table  数据
              tableData:[],
              loading:false,  //table  loading
          },
          dialogData: {   // 弹窗数据
              title: '添加信使信息',
              isShow: false
          },

          formData:{   //弹窗数据
              ArticleTitle: '',
              GroupType: '1',
              Period: '1',
              ArticleContent: ''

          },
          rules: { // 表单验证
              ArticleTitle: [
                    { required: true, message: '必填项', trigger: 'blur' }
                ],
              ArticleContent: [
                  { required: true, validator:ArticleContent , trigger: 'blur' }
              ],

          },
          GroupTypeFilter(row, column, cellValue, index){
                return cellValue=='1'?'A':'B'
          },
          studyOptions:  [  //  研究阶段数据
              {
                  Name: "A",
                  value: "1"
              },
              {
                  Name: "B",
                  value: "2"
              }
          ],
          applicableOptiona:DIC_PERIODB,
          contents:''
      }
    },

    watch:{
      "periodModel": function(value) {
       
        this.loading = true
      
        this.getList()
      }
    },
    created() {
      this.getList()
    },
    mounted () {
    },
    methods: {
        deleData (){  // 每次点开之前 清空数据
                this.formData = {
                    ArticleTitle: '',
                    GroupType: this.searchData.groupType,
                    ArticleContent: '',
                    Period:this.Period
                };
                this.aa = {
                     ArticleContent : ''
                }
        },

        closeDialog (){  //监听窗口关闭后清掉验证
            this.$refs['addressForm'].resetFields();
        },

        getList() {   // 获取首页数据
            let data = { ...this.searchData,
            period:this.periodModel }
            this.table.tableData = []
            this.laoding = true;
            this.service({
                url:"Message/GetHealthEducationArticle",
                method: "get",
                params: data
            }).then( (res)=> {

                if (res.isSuccess) {
                  this.table.tableData = res.dtData
                }
                this.loading = false;

            }).catch((error)=> {
                console.log(error)
            })
        },

        queryHandler() { // 用户点击查询事件
            this.getList()
        },

        addHandler() {  //添加事件
            this.deleData()
            this.dialogData.isShow = true;
            this.dialogData.title = '添加信使信息'
            this.hackReset = false
            this.$nextTick(() => {
                this.hackReset = true
            })
        },

      changePositionHandler(direction, index, row) {
        // direction:1: 向上， -1 ： 向下；

        let tmpIndex;
        let tmpItem;
        let arr = [];


        if (direction == 1) {
          // 排在第一的不可以在向上
            if (index <= 0) {
              return;
            }
                tmpIndex = index - 1;
                tmpItem = this.table.tableData[tmpIndex];
                let num =  row.ArticleIndex;
                row.ArticleIndex = tmpItem.ArticleIndex
                tmpItem.ArticleIndex = num

              if (!tmpItem) {
                tmpIndex = this.table.tableData.length - 1;
                tmpItem = this.table.tableData[tmpIndex];
              }

        } else {
          // 排在最下面的不在刻意向下
              if (index >= this.table.tableData.length - 1) {
                return;
              }
              tmpIndex = index + 1;
              tmpItem = this.table.tableData[tmpIndex];
                let num =  row.ArticleIndex;
                row.ArticleIndex = tmpItem.ArticleIndex
                tmpItem.ArticleIndex = num
              if (!tmpItem) {
                tmpIndex = 0;
                tmpItem = this.table.tableData[tmpIndex];
              }
        }
        arr.push(row)
        arr.push(tmpItem)
        this.changeSort(arr);
    },
        changeSort(item) {

          this.formData.UserType = this.userType;
          this.service({
              url: "Message/SaveHealthEducationArticleIndex",
              method: "post",
              data: {
                listHealthEducationArticleObj: item
              }
            })
            .then(res=> {
              if (res.isSuccess){
                 this.$message({
                          message: res.msg,
                          type: 'success'
                    });
                    this.getList();
              }else {
                  this.$message({
                          message: '保存失败',
                          type: 'success'
                    });
              }


            })
            .catch(error => {
              // that.getList();
              console.log(error)
              this.loading = false;
            });
        },
        saveHandler () {   // 弹窗数据保存
            this.formData.ArticleContent=JSON.parse(JSON.stringify(this.contents))
            this.$refs.addressForm.validate(valid => {
                if(valid) {
                    this.fullscreenLoading = true;
                    this.service({
                        url: 'Message/SaveHealthEducationArticle',
                        method: 'post',
                        data: {
                          ...this.formData
                        }
                    }).then ((res) =>{
                        this.fullscreenLoading= false;
                        this.dialogData.isShow = false;
                        this.$message({
                          message: '保存成功',
                              type: 'success'
                            });
                            this.getList();
                        })
                    }else {
                       this.$message({
                          message: '验证失败',
                          type: 'warning'
                    });
                    }
                })
        },
        handleClick(data) {    // 数据修改

            this.dialogData.isShow = true;
            this.dialogData.title = '编辑信使信息';
              this.hackReset = false
            this.$nextTick(() => {
                this.hackReset = true
            })
            this.formData = {...data}
            this.contents=this.formData.ArticleContent
        },

        deleteHandler(index, row) {   // 数据删除
              this.$confirm("是否删除本事项？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              }).then(()=>{
                this.service({
                    url: "Message/DeleteHealthEducationArticle?SYS_ID=" + row.SYS_ID,
                    data: { ...row },
                    method: "post"
                }).then((res) =>{
                  if (res.isSuccess){
                        this.$message({
                          message: res.msg,
                          type: 'success'
                        });
                        this.getList()
                  }
                })
              })
        },
        onchangeEditor(a)  {   // 组件回调
            this.contents=a
        }
    }
}
</script>

<style  lang= "scss" >
    .el-dialog__body {
        max-height: 400px;
        overflow: auto;
    }
  .editor {
    margin-top: 40px;
  }
  .pd-bt {
      padding: 12px 30px
  }

  .arrow-top {
        position: relative;
        display: inline-block;
        box-sizing: border-box;
        width: 8px;
        height: 8px;
        border: 1px solid #409eff;
        border-width: 1px 0 0 1px;
        transform: rotate(45deg) translateY(-50%);
    }
.arrow-top:before {
    content: "";
    position: absolute;
    height: 1px;
    width: 12px;
    background-color: #409eff;
    left: 0;
    top: -1px;
    transform: rotate(45deg);
    transform-origin: 0 0;
  }

.arrow-bottom {
  position: relative;
  display: inline-block;
  box-sizing: border-box;
  width: 8px;
  height: 8px;
  border: 1px solid #409eff;
  border-width: 0 1px 1px 0;
  transform: rotate(45deg);
}
   .arrow-bottom:before {
        content: "";
        position: absolute;
        height: 1px;
        width: 12px;
        background-color: #409eff;
        right: 0;
        bottom: 0;
        transform: rotate(45deg);
        transform-origin: 100% 0;
    }
</style>


